<template>
  <div class="search">
    <Back>
      <template #back-right>
        <div class="search-ipt">
          <input
            class="ipt-box"
            type="text"
            placeholder="输入商品名称关键字"
            v-model="keyword"
            @input="search"
          />
        </div>
      </template>
    </Back>

    <!-- 搜索历史记录 -->
    <div class="search-history" v-show="keywords.length > 0">
      <div class="history-box">
        <div
          class="history-item"
          v-for="(item, index) in keywords"
          :key="index"
          @click="quickSearch(item.title)"
        >
          {{item.title}}
          <van-icon @click.stop="removeOne(index)" name="cross" />
        </div>
      </div>
      <div class="search-btn" @click="clearAll">清除所有搜索历史</div>
    </div>

    <!-- 搜索商品数据 -->
    <div class="pro-box">
      <div
        class="pro-item"
        v-for="(item, index) in products"
        :key="index"
        @click="viewDetail(item.pid)"
      >
        <ProItem :product="item" />
      </div>
    </div>
  </div>
</template>

<script>
import Back from "../components/Back.vue";
import ProItem from "../components/ProItem.vue";
export default {
  name: "Search",

  components: {
    Back,
    ProItem,
  },

  data() {
    return {
      //定时器序号
      timer: null,

      //商品名称关键字
      keyword: "",

      //商品数据
      products: [],

      //所有搜索过的关键字, 最多10个
      keywords: [],
    };
  },

  created() {
    this.searchProduct()
    //获取搜索历史记录
    let historySearch = localStorage.getItem("historySearch");
        if (historySearch) {
      this.keywords.push(...JSON.parse(historySearch));
    }
  },

  methods: {
    //搜索
    searchProduct() {
      if (this.keyword.trim() === "") {
        return;
      }

      this.axios({
        method: "get",
        url: "/search",
        params: {
          name: this.keyword,
        },
      })
        .then((res) => {
          console.log("res==>",res);
                    if (res.data.code === "Q001") {
            this.products = res.data.result;

            if (res.data.result.length > 0) {
              //验证是否存在重复的关键字
              for (let i = 0; i < this.keywords.length; i++) {
                if (this.keywords[i].title === this.keyword) {
                  return;
                }
              }

              //是否搜索关键字超出10个, 则移除第一个关键字
              if (this.keywords.length === 10) {
                this.keywords.splice(0, 1);
              }

              this.keywords.push({ title: this.keyword });
              localStorage.setItem(
                "historySearch",
                JSON.stringify(this.keywords)
              );

                          }
          }
        })
        .catch((err) => {
                  });
    },

    //输入关键字搜索
    search() {
      //使用函数节流控制触发函数执行的频率
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
                //获取输入商品名称关键字
        this.searchProduct();
              }, 500);
    },

    //查看商品详情
    viewDetail(pid) {
      this.$router.push({ name: "Detail", params: { pid } });
    },

    //点击搜索关键字进行快速搜索
    quickSearch(keyword) {
            if (this.keyword === keyword) {
                return;
      }
      this.keyword = keyword;
      this.searchProduct();
    },

    //单个删除关键字
    removeOne(index) {
            this.keywords.splice(index, 1);
      localStorage.setItem("historySearch", JSON.stringify(this.keywords));
    },

    //删除所有搜索关键字
    clearAll() {
      //清空数组
      this.keywords = [];
      localStorage.setItem("historySearch", JSON.stringify(this.keywords));
    }
  },
};
</script>

<style lang="less" scoped>
.pro-box {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
}

.pro-item {
  width: calc(~"100% / 3 - 10px + 10px / 3");
  background-color: #fff;
  margin-bottom: 10px;
  margin-right: 10px;

  &:nth-child(3n) {
    margin-right: 0;
  }
}
.search-btn {
  height: 26px;
  background-color: #e8e8e8;
  width: 160px;
  text-align: center;
  line-height: 26px;
  margin: 20px auto 10px;
  color: #666;
  border-radius: 13px;
  font-size: 14px;
}

.search-history {
  background-color: #fff;
  padding-bottom: 20px;
}
.history-box {
  padding: 10px 10px 0 0;
  &:after {
    display: block;
    content: "";
    clear: both;
  }
}

/deep/ .product-box {
  padding: 10px;
}

.history-item {
  float: left;
  margin-left: 10px;
  margin-bottom: 10px;
  background-color: #e8e8e8;
  padding: 2px 5px;
}
/deep/ .van-nav-bar__right {
  width: calc(~"100% - 80px");
  padding: 0;
}

.search-ipt {
  flex: 1;
  margin-right: 10px;
  background-color: #f5f5f5;
  height: 28px;
  border-radius: 14px;
  overflow: hidden;
  padding: 0 14px;
}

.ipt-box {
  border: none;
  outline: none;
  background-color: transparent;
  padding: 0;
  display: block;
  width: 100%;
  height: 100%;
}
</style>